<template>
  <div>
    <input type="text" v-model="name" placeholder="codercqw" />
    <input type="text" v-model="password" placeholder="123456" />
    <button @click="login">提交</button>
  </div>
</template>

<script>
import { reactive, toRefs } from 'vue'
import { useStore } from 'vuex'
import { useRoute, useRouter } from 'vue-router'
export default {
  name: 'login',
  setup() {
    const store = useStore()
    const route = useRoute()
    const router = useRouter()
    let redirect
    let otherQuery
    const getOtherQuery = query => {
      return Object.keys(query).reduce((acc, cur) => {
        if (cur !== 'redirect') {
          acc[cur] = query[cur]
        }
        return acc
      }, {})
    }
    let userInfo = reactive({
      name: '',
      password: ''
    })
    if (route.query) {
      redirect = route.query.redirect
      otherQuery = getOtherQuery(route.query)
    }
    let login = async () => {
      try {
        await store.dispatch('user/login', userInfo)
        router.push({ path: redirect || '/', query: otherQuery })
      } catch (err) {
        alert(err)
      }
    }

    return {
      ...toRefs(userInfo),
      login
    }
  }
}
</script>

<style scoped lang="scss"></style>
